<script lang="ts" setup>
import {ref} from 'vue';
import type {UploadProps, UploadUserFile} from 'element-plus';

import ImagePreview from '../components/preview/ImagePreview.vue';
import PdfPreview from '../components/preview/PdfPreview.vue';
import VideoPreview from '../components/preview/VideoPreview.vue';
import FilePreview from '../components/preview/FilePreview.vue';

import One from '../components/template/one.vue';
import {devUploadProps} from './upload';

const props = defineProps(devUploadProps);

const fileList = ref<UploadUserFile[]>([]);

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  return true;
};

const handleSuccess: UploadProps['onSuccess'] = (response, file, fileListVal) => {
  fileList.value = fileListVal;
};

const handleRemove: UploadProps['onRemove'] = (file, fileListVal) => {
  fileList.value = fileListVal;
};

/**
 * 获取预览组件
 * @param file
 */
const getPreviewComponent = (file: UploadUserFile) => {
  const type = file.raw?.type || '';
  if (type.startsWith('image/')) return ImagePreview;
  if (type === 'application/pdf') return PdfPreview;
  if (type.startsWith('video/')) return VideoPreview;
  return FilePreview;
};

/**
 * 获取模版组件类型
 * @param file
 */
const getTemplateComponent = (type:string) => {
  if (type ==='one') return One;
  return One;
};

// 定义组件名称
defineOptions({
  name: 'DevUpload',
  inheritAttrs: false
});
</script>

<template>
  <el-upload
      ref="uploadRef"
      class="custom-upload"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :file-list="fileList"
      list-type="picture-card"
      v-bind="$attrs"
  >
    <component :is="getTemplateComponent('one')"></component>
  </el-upload>

  <div v-if="props.preview" class="preview-list">
    <div v-for="(file, index) in fileList" :key="index" class="preview-item">
      <component :is="getPreviewComponent(file)" :file="file"/>
    </div>
  </div>
</template>

<style scoped>
.custom-upload {
  margin-bottom: 16px;
}

.preview-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.preview-item {
  width: 200px;
}
</style>
